import axios from "axios"

export default {
    namespaced: true,
    // 要返回一个对象
    state: () => ({
        cart: []
    }),
    mutations: {
        // 第一个参数一定是state
        updateCart(state, cart) {
            state.cart = cart
            console.log(state.cart);
        },
        updateCartState(state, payload) {
            let index = state.cart.findIndex(item => item.id == payload.id)
            state.cart[index].goods_state = payload.value
        },
        updateCartCount(state, payload) {
            let index = state.cart.findIndex(item => item.id == payload.id)
            state.cart[index].goods_count = payload.value
        },
        updateAllState(state, val) {
            console.log(val);
            state.cart.forEach(item => item.goods_state = val);
            console.log(state.cart);
        }
    },
    actions: {
        // 在actions中封装一个获取购物车列表的函数
        // 在这个函数中要异步发请求
        // 发请求
        async getCartList(context) {
            let res = await axios.get("https://www.escook.cn/api/cart")
            // console.log(res.data);
            context.commit("updateCart", res.data.list)
        }
    },
    getters: {
        // 只能写函数m表示计算属性的get函数,不能写set
        allPrice(state) {
            // 求所有已选中商品的总价
            return state.cart.filter(item => item.goods_state).reduce((sum, item) => sum += item.goods_count * item.goods_price, 0)
        },
        allCount(state) {
            return state.cart.filter(item => item.goods_state).reduce((sum, item) => sum += item.goods_count,0)
        }
    }
}